// Copyright 2022 The Molego Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package translate

import (
	utils "gitee.com/west0207/molego/core/utils"

	etree "gitee.com/west0207/etree"
)

// 获取重命名表的Entity标签的sql语句
// dbmsName *string 数据库类型名称，例如：mysql
// dbmsVersion *string 数据库系统版本，例如：5
// renameTableEle *etree.Element 重命名表的Entity标签
func GetRenameTableSql(dbmsName *string, dbmsVersion *string, renameTableEle *etree.Element) (string, error) {
	return getDefaultRenameTableSql(dbmsName, dbmsVersion, renameTableEle)
}

// <renameTable oldTableName="test_rename_table" newTableName="test_rename_table_new" />
// 如下为通用模式，例如mysql v8+, PostgreSQL v12+, Oracle, SQLite...
// alter table test_t02 rename to test_t02_new;
func getDefaultRenameTableSql(dbmsName *string, dbmsVersion *string, renameTableEle *etree.Element) (string, error) {
	oldTableName := renameTableEle.SelectAttrValue("oldTableName", utils.EMPTY)
	SetPropertyValue(dbmsName, &oldTableName)
	newTableName := renameTableEle.SelectAttrValue("newTableName", utils.EMPTY)
	SetPropertyValue(dbmsName, &newTableName)

	var sql string
	switch *dbmsName {
	case MsSQLServer:
		// exec sp_rename 'test_column_type', 'test_column_type_new';
		sql = "exec sp_rename '" + oldTableName + "', '" + newTableName + "';" + utils.LF
	default:
		// alter table test_t02 rename to test_t02_new;
		sql = "alter table " + oldTableName + " rename to " + newTableName + utils.SEMICOLON + utils.LF
	}

	return sql, nil
}
